<template>
  <div class="learning-process-container">
    <!-- 相关性分析卡片 -->
    <el-row :gutter="20" class="correlation-analysis">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>学习时长与成绩相关性分析</span>
          </div>
          <div class="correlation-content">
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="correlationChart" style="width: 100%; height: 400px;"></div>
              </el-col>
              <!-- <el-col :span="12">
                <div class="analysis-text">
                  <h4>分析结论：</h4>
                  <p>1. 学习时长与成绩呈正相关关系：</p>
                  <ul>
                    <li>学习时长 &gt;= 8小时/周：成绩优秀（85-96分）</li>
                    <li>学习时长 5-8小时/周：成绩良好（70-85分）</li>
                    <li>学习时长 &lt; 5小时/周：成绩待提升（40-70分）</li>
                  </ul>
                  <p>2. 学习行为指标：</p>
                  <ul>
                    <li>视频观看次数：与学习时长成正比</li>
                    <li>视频重播率：学习时长越长，重播率越高</li>
                    <li>在线时长：学习时长增加，在线时长同步提升</li>
                  </ul>
                </div>
              </el-col> -->
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 电磁感应章节分析 -->
    <el-row :gutter="20" class="electromagnetic-analysis" style="margin-top: 20px;">
      <el-col :span="24">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>电磁感应章节学习行为分析</span>
          </div>
          <div class="electromagnetic-content">
            <el-row :gutter="20">
              <el-col :span="14">
                <div ref="electromagneticChart" style="width: 100%; height: 500px;"></div>
              </el-col>
              <!-- <el-col :span="10">
                <div class="analysis-text">
                  <h4>分析结论：</h4>
                  <p>1. 观看行为分析：</p>
                  <ul>
                    <li>高频率观看（≥15次）：{{ electromagneticStats.watchCountStats.high }}人</li>
                    <li>中等频率（10-15次）：{{ electromagneticStats.watchCountStats.medium }}人</li>
                    <li>低频率观看（&lt;10次）：{{ electromagneticStats.watchCountStats.low }}人</li>
                  </ul>
                  <p>2. 重播行为分析：</p>
                  <ul>
                    <li>高重播率（≥70%）：{{ electromagneticStats.replayRateStats.high }}人</li>
                    <li>中等重播率（50-70%）：{{ electromagneticStats.replayRateStats.medium }}人</li>
                    <li>低重播率（&lt;50%）：{{ electromagneticStats.replayRateStats.low }}人</li>
                  </ul>
                  <p>3. 操作行为分析：</p>
                  <ul>
                    <li>总倒退次数：{{ electromagneticStats.operationStats.rewindCount }}次</li>
                    <li>总快进次数：{{ electromagneticStats.operationStats.fastForwardCount }}次</li>
                    <li>平均观看时长：{{ electromagneticStats.avgWatchDuration }}分钟</li>
                  </ul>
                </div>
              </el-col> -->
            </el-row>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 搜索区域 -->
    <div class="filter-container">
      <el-form :inline="true" :model="listQuery" class="demo-form-inline">
        <el-form-item label="学生姓名">
          <el-input
            v-model="listQuery.name"
            placeholder="请输入学生姓名"
            clearable
            @keyup.enter.native="handleFilter"
          />
        </el-form-item>
        <el-form-item label="班级">
          <el-select v-model="listQuery.class" placeholder="请选择班级" clearable>
            <el-option label="初二(1)班" value="初二(1)班" />
            <el-option label="初二(2)班" value="初二(2)班" />
            <el-option label="初二(3)班" value="初二(3)班" />
            <el-option label="初二(4)班" value="初二(4)班" />
          </el-select>
        </el-form-item>
        <el-form-item label="学科">
          <el-select v-model="listQuery.subject" placeholder="请选择学科" clearable>
            <el-option label="语文" value="语文" />
            <el-option label="数学" value="数学" />
            <el-option label="英语" value="英语" />
            <el-option label="物理" value="物理" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      style="width: 100%"
      border
    >
      <el-table-column prop="name" label="学生姓名" />
      <el-table-column prop="class" label="班级" width="100" />
      <el-table-column prop="subject" label="学科" width="80" />
      <el-table-column label="学习情况" width="120">
        <template slot-scope="{row}">
          <el-tooltip :content="`学习时长：${row.courseTimeData.find(c => c.course === '数学').time}`" placement="top">
            <el-progress
              :percentage="row.courseTimeData.find(c => c.course === '数学').progress"
              :color="getProgressColor(row.courseTimeData.find(c => c.course === '数学').progress)"
            ></el-progress>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="dailyLogins" label="日均登录次数" width="120" />
      <el-table-column prop="avgOnlineTime" label="平均在线时长" width="120">
        <template slot-scope="{row}">
          {{ row.avgOnlineTime }}分钟
        </template>
      </el-table-column>
      <el-table-column prop="activityLevel" label="学习活跃度" width="100">
        <template slot-scope="{row}">
          <el-tag :type="getActivityTagType(row.activityLevel)">
            {{ row.activityLevel }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="weeklyStudyHours" label="每周学习时长" width="120">
        <template slot-scope="{row}">
          {{ row.weeklyStudyHours }}小时
        </template>
      </el-table-column>
      <el-table-column prop="videoWatchCount" label="视频观看次数" width="120" />
      <el-table-column prop="videoReplayRate" label="视频重播率" width="100">
        <template slot-scope="{row}">
          {{ row.videoReplayRate }}%
        </template>
      </el-table-column>
      <el-table-column label="操作" width="120">
        <template slot-scope="{row}">
          <el-button type="text" @click="handleDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="学习过程详情" width="70%">
      <div v-if="selectedStudent">
        <!-- 登录行为分析 -->
        <div class="detail-section">
          <h3>登录行为分析</h3>
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="data-item">
                  <div class="title">日均登录次数</div>
                  <div class="value">{{ selectedStudent.dailyLogins }}</div>
                  <div class="trend" :class="selectedStudent.loginTrend > 0 ? 'up' : 'down'">
                    <i :class="selectedStudent.loginTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(selectedStudent.loginTrend) }}%
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="data-item">
                  <div class="title">平均在线时长</div>
                  <div class="value">{{ selectedStudent.avgOnlineTime }}分钟</div>
                  <div class="trend" :class="selectedStudent.timeTrend > 0 ? 'up' : 'down'">
                    <i :class="selectedStudent.timeTrend > 0 ? 'el-icon-top' : 'el-icon-bottom'"></i>
                    {{ Math.abs(selectedStudent.timeTrend) }}%
                  </div>
                </div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card shadow="hover">
                <div class="data-item">
                  <div class="title">学习活跃度</div>
                  <div class="value">{{ selectedStudent.activityLevel }}</div>
                  <el-progress :percentage="selectedStudent.activityPercentage" :color="activityColor"></el-progress>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>

        <!-- 课程学习时长分析 -->
        <div class="detail-section">
          <h3>课程学习时长分析</h3>
          <div class="chart-container">
            <div ref="courseTimeChart" style="width: 100%; height: 300px;"></div>
          </div>
        </div>

        <!-- 视频学习行为分析 -->
        <div class="detail-section">
          <h3>视频学习行为分析</h3>
          <div class="chart-container">
            <div ref="videoBehaviorChart" style="width: 100%; height: 300px;"></div>
          </div>
          <div class="chart-container" style="margin-top: 20px;">
            <div ref="videoDetailChart" style="width: 100%; height: 300px;"></div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import Pagination from '@/components/Pagination'
import { learningProcessData, electromagneticStats } from '@/mock/learning-process'

export default {
  name: 'LearningProcess',
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      list: [],
      total: 0,
      dialogVisible: false,
      selectedStudent: null,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: '数学'
      },
      mockData: learningProcessData,
      electromagneticStats,
      activityColor: [
        { color: '#f56c6c', percentage: 60 },
        { color: '#e6a23c', percentage: 80 },
        { color: '#67c23a', percentage: 100 }
      ]
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.initCorrelationChart()
    this.initElectromagneticChart()
  },
  methods: {
    getList() {
      this.listLoading = true
      setTimeout(() => {
        let result = [...this.mockData]
        const { name, class: className, subject } = this.listQuery

        if (name) {
          result = result.filter(item => item.name.includes(name))
        }
        if (className) {
          result = result.filter(item => item.class === className)
        }
        if (subject) {
          result = result.filter(item => item.subject === subject)
        }

        this.total = result.length
        const { page, limit } = this.listQuery
        const start = (page - 1) * limit
        const end = page * limit
        this.list = result.slice(start, end)
        this.listLoading = false
      }, 500)
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetQuery() {
      this.listQuery = {
        page: 1,
        limit: 10,
        name: undefined,
        class: undefined,
        subject: '数学'
      }
      this.getList()
    },
    getActivityTagType(level) {
      switch (level) {
        case '高':
          return 'success'
        case '中':
          return 'warning'
        case '低':
          return 'danger'
        default:
          return 'info'
      }
    },
    handleDetail(row) {
      this.selectedStudent = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.initCourseTimeChart()
        this.initVideoBehaviorChart()
      })
    },
    initCourseTimeChart() {
      const chart = echarts.init(this.$refs.courseTimeChart)
      const option = {
        title: {
          text: '各科目学习时长分布'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.selectedStudent.courseTimeData.map(item => item.course)
        },
        yAxis: {
          type: 'value',
          name: '时长(小时/周)'
        },
        series: [{
          data: this.selectedStudent.courseTimeData.map(item => parseInt(item.time)),
          type: 'bar',
          showBackground: true,
          backgroundStyle: {
            color: 'rgba(180, 180, 180, 0.2)'
          }
        }]
      }
      chart.setOption(option)
    },
    initVideoBehaviorChart() {
      const chart = echarts.init(this.$refs.videoBehaviorChart)
      const option = {
        title: {
          text: '视频学习行为分析'
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: ['观看次数', '平均观看时长', '重播率']
        },
        xAxis: {
          type: 'category',
          data: this.selectedStudent.videoLearningData.map(item => item.chapter)
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            name: '观看次数',
            type: 'line',
            data: this.selectedStudent.videoLearningData.map(item => item.watchCount)
          },
          {
            name: '平均观看时长',
            type: 'line',
            data: this.selectedStudent.videoLearningData.map(item => item.avgDuration)
          },
          {
            name: '重播率',
            type: 'line',
            data: this.selectedStudent.videoLearningData.map(item => item.replayRate)
          }
        ]
      }
      chart.setOption(option)

      // 初始化详细视频行为图表
      const detailChart = echarts.init(this.$refs.videoDetailChart)
      const detailOption = {
        title: {
          text: '视频操作行为分析'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['快进次数', '倒退次数']
        },
        xAxis: {
          type: 'category',
          data: this.selectedStudent.videoLearningData.map(item => item.chapter)
        },
        yAxis: {
          type: 'value',
          name: '操作次数'
        },
        series: [
          {
            name: '快进次数',
            type: 'bar',
            data: this.selectedStudent.videoLearningData.map(item => item.fastForwardCount)
          },
          {
            name: '倒退次数',
            type: 'bar',
            data: this.selectedStudent.videoLearningData.map(item => item.rewindCount)
          }
        ]
      }
      detailChart.setOption(detailOption)
    },
    getProgressColor(progress) {
      if (progress >= 90) return '#67C23A'
      if (progress >= 75) return '#E6A23C'
      if (progress >= 60) return '#909399'
      return '#F56C6C'
    },
    initCorrelationChart() {
      const chart = echarts.init(this.$refs.correlationChart)

      // 处理数据
      const data = this.mockData.map(item => ({
        name: item.name,
        studyHours: item.weeklyStudyHours,
        progress: item.courseTimeData.find(c => c.course === '数学').progress
      }))

      // 按学习时长排序
      data.sort((a, b) => a.studyHours - b.studyHours)

      const option = {
        title: {
          text: '学习时长与成绩相关性分析',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
            return `学生：${params[0].name}<br/>学习时长：${params[0].value}小时/周<br/>成绩：${params[1].value}分`
          }
        },
        legend: {
          data: ['学习时长', '成绩'],
          top: 30
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.name),
          name: '学生',
          nameLocation: 'middle',
          nameGap: 20,
          axisLabel: {
            interval: 'auto',
            rotate: 45
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '学习时长(小时/周)',
            min: 0,
            max: 12
          },
          {
            type: 'value',
            name: '成绩(分)',
            min: 0,
            max: 100
          }
        ],
        series: [
          {
            name: '学习时长',
            type: 'bar',
            data: data.map(item => ({
              value: item.studyHours,
              name: item.name
            }))
          },
          {
            name: '成绩',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => ({
              value: item.progress,
              name: item.name
            }))
          }
        ]
      }

      chart.setOption(option)
    },
    initElectromagneticChart() {
      const chart = echarts.init(this.$refs.electromagneticChart)
      const option = {
        title: {
          text: '电磁感应章节学习行为分布',
          left: 'center',
          top: 20
        },
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c}人 ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: '5%',
          top: 'middle',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: {
            fontSize: 12
          }
        },
        series: [
          {
            name: '观看频率分布',
            type: 'pie',
            radius: ['25%', '40%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}人',
              fontSize: 12,
              lineHeight: 16,
              distanceToLabelLine: 5
            },
            labelLine: {
              length: 10,
              length2: 5,
              smooth: true,
              maxSurfaceAngle: 80
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            data: [
              { value: electromagneticStats.watchCountStats.high, name: '高频率观看' },
              { value: electromagneticStats.watchCountStats.medium, name: '中等频率' },
              { value: electromagneticStats.watchCountStats.low, name: '低频率观看' }
            ]
          },
          {
            name: '重播率分布',
            type: 'pie',
            radius: ['50%', '65%'],
            center: ['40%', '50%'],
            avoidLabelOverlap: true,
            itemStyle: {
              borderRadius: 4,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: true,
              position: 'outside',
              formatter: '{b}\n{c}人',
              fontSize: 12,
              lineHeight: 16,
              distanceToLabelLine: 5
            },
            labelLine: {
              length: 10,
              length2: 5,
              smooth: true,
              maxSurfaceAngle: 80
            },
            emphasis: {
              label: {
                show: true,
                fontSize: 14,
                fontWeight: 'bold'
              }
            },
            data: [
              { value: electromagneticStats.replayRateStats.high, name: '高重播率' },
              { value: electromagneticStats.replayRateStats.medium, name: '中等重播率' },
              { value: electromagneticStats.replayRateStats.low, name: '低重播率' }
            ]
          }
        ]
      }
      chart.setOption(option)
    }
  }
}
</script>

<style lang="scss" scoped>
.learning-process-container {
  padding: 20px;

  .correlation-analysis {
    margin-bottom: 20px;

    .correlation-content {
      .analysis-text {
        padding: 20px;

        h4 {
          margin-bottom: 15px;
          color: #303133;
        }

        p {
          margin: 10px 0;
          color: #606266;
        }

        ul {
          padding-left: 20px;
          color: #606266;

          li {
            margin: 5px 0;
          }
        }
      }
    }
  }

  .electromagnetic-analysis {
    margin-top: 20px;

    .electromagnetic-content {
      .analysis-text {
        padding: 20px;
        height: 500px;
        overflow-y: auto;

        h4 {
          margin-bottom: 15px;
          color: #303133;
          font-size: 16px;
        }

        p {
          margin: 15px 0 10px;
          color: #606266;
          font-size: 14px;
        }

        ul {
          padding-left: 20px;
          color: #606266;
          margin-bottom: 15px;

          li {
            margin: 8px 0;
            font-size: 13px;
            line-height: 1.5;
          }
        }
      }
    }
  }

  .filter-container {
    padding-bottom: 10px;
  }

  .detail-section {
    margin-bottom: 30px;

    h3 {
      margin-bottom: 20px;
      font-weight: 500;
      color: #303133;
    }
  }

  .data-item {
    text-align: center;
    padding: 20px;

    .title {
      font-size: 14px;
      color: #909399;
      margin-bottom: 10px;
    }

    .value {
      font-size: 24px;
      font-weight: bold;
      color: #303133;
      margin-bottom: 10px;
    }

    .trend {
      font-size: 12px;

      &.up {
        color: #67C23A;
      }

      &.down {
        color: #F56C6C;
      }
    }
  }

  .chart-container {
    background: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  }
}
</style>
